#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>

//#define MYPATH myshm
char *MYPATH = "myshm";
int iRet = 256;

void thread_handle(void)
{
	sem_t *sem = NULL;
	int shm_id;
	char my_array[20];
	char *buffer = NULL;
	pthread_t tid;
//	int iRet = 2;
	bzero(my_array,sizeof(my_array));
	shm_id = shm_open(MYPATH,O_RDWR|O_CREAT,0644);
	ftruncate(shm_id,100);
	sem = sem_open(MYPATH,O_CREAT,0644,1);
	buffer = mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
	
	while(fgets(my_array,20,stdin)!=NULL)
	{	
		sem_wait(sem);
		strcpy(buffer,my_array);
	    printf("buffer:%s\n",buffer);	
		sem_post(sem);
		if(strcmp(buffer,"q\n")==0)
		{
			break;
//		pthread_exit(0);
		}
		sleep(2);
		bzero(my_array,sizeof(my_array));
	}
	tid = pthread_self();
	printf("pid %d thread id is %lu\n",getpid(),tid);
	printf("&iRet %d\n",(int)&iRet);
	pthread_exit(&iRet);
}

int main()
{
	int shm_id;
	pthread_t tid1;
	sem_t *sem = NULL;
	char *buffer = NULL;
	void *iRet;
	shm_id = shm_open(MYPATH,O_RDWR|O_CREAT,0644);
	ftruncate(shm_id,100);
	sem = sem_open(MYPATH,O_CREAT,0644,1);
	buffer = mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
	strncpy(buffer,"0",100);
//	strcpy(buffer,"q\n");

	if(pthread_create(&tid1,NULL,(void*)thread_handle,NULL) != 0)
	{
		return -1;
	}
	while(1)
	{
		if(strcmp(buffer,"0")==0)
		{
			continue;
		}
		else
		{
			if(strcmp(buffer,"q\n")==0)
			{
				break;
			}
			else
			{
				sem_wait(sem);
				printf("get from thread %lu : %s\n",tid1,buffer);
				strncpy(buffer,"0",100);
				sem_post(sem);
			}
		}
	}
	shm_unlink(MYPATH);
	sem_unlink(MYPATH);

	sleep(3);
	pthread_join(tid1,(void**)&iRet);
	printf("pid %d  thread id %lu exit with %d\n",getpid(),tid1,*(int *)iRet);
}
